<template>
    <div class="busLine-by-id">
        <van-nav-bar left-arrow @click-left="$router.back(-1)" :fixed="true" :title="translateString(busLineName)"/>
        <div style="padding: 23px"></div>
        <van-tabs class="map-tabs"
                  :line-width="tabWidth"
                  sticky
                  :offset-top="46"
                  v-model="activeTab">
            <van-tab :title="$t('m.Map')">
                <gmap-map
                    :center="center"
                    :zoom="11"
                    :options="mapControls"
                    :style="mapStyle"
                    v-show="loadingData"
                    ref="map"
                >
                    <gmap-marker
                        v-show="userMarkers.lat && userMarkers.lng"
                        key="user-location"
                        :position="userMarkers"
                        :icon="userLocationIcon"
                    ></gmap-marker>
                    <gmap-marker
                        :key="index"
                        v-for="(m, index) in markers"
                        :position="m.position"
                        :icon="icon"
                        @click="showInfoWin(m)"
                    ></gmap-marker>
                    <GmapInfoWindow
                        :opened="infoWinOpen"
                        :position="infoWindowPos"
                        @closeclick="closeClick"
                    >
                        <div class="info-title g-font" @click="getBusLineListByStop('')">
                            <div class="title-left g-font">{{infoWindowTitle}}</div>
                            <div class="title-right"></div>
                        </div>
                        <div class="g-font">{{infoWindowLineNub}}</div>
                    </GmapInfoWindow>
                    <gmap-polyline
                        :options="options"
                        :path="linePath"
                        :icon="icon"
                    ></gmap-polyline>
                </gmap-map>
            </van-tab>
            <van-tab :title="$t('m.Stops')">
                <div class="stop-list-box">
                    <div class="stop-list-item" v-for="(items, index) in markers" :key="index"  @click="getBusLineListByStop(items)">
                        <div class="item-left" :style="headBackColor">{{getLineNum(busLineNo)}}</div>
                        <div class="item-right">
                            <div class="item-title">{{getLineNumStr(busLineNo)}}</div>
                            <div class="item-info">{{getTranslationName(items.info, 'name')}} ({{getTranslationName(items.info, 'township')}})</div>
                            <div class="item-info">{{getTranslationName(items.info, 'road')}}</div>
                        </div>
                    </div>
                </div>
            </van-tab>
        </van-tabs>
        <!--请求的经过某站点的路线集合弹出层-->
        <van-popup v-model="busLineListShow" class="bus-line-pop">
            <div class="list-loading" v-if="listLoading">
                <van-loading type="spinner" />
            </div>
            <div class="line-list-box" v-else :style="popHeight">
                <div class="line-list-title">
                    <div class="line-title">{{infoWindowStopInfo.name}}</div>
                    <div class="line-info">{{infoWindowStopInfo.road}}</div>
                    <div class="line-info">{{infoWindowStopInfo.township}}</div>
                </div>
                <div class="line-list-outbox">
                    <div class="line-list-inbox">
                        <div class="stop-list-item" v-for="(items, index) in busLineList" :key="index" @click="goToOtherLineData(items)">
                            <div class="item-left" :style="'background-color:' + items.color">{{getLineNum(items.lineNum)}}</div>
                            <div class="item-right">
                                <div class="item-title">{{getLineNumStr(items.lineNum)}}</div>
                                <div class="item-info">{{translateString(items.start)}}</div>
                                <div class="item-info">{{translateString(items.end)}}</div>
                            </div>
                        </div>
                    </div>
                </div>

            </div>
        </van-popup>
    </div>
</template>

<script>
    import {getBusRoute, busRouteDetail, busLineListByStop} from '../../static/api/mgc_api'
    import {gmapApi} from 'vue2-google-maps'
    export default {
        name: "GoogleMap",
        computed: {
            google: gmapApi
        },
        data() {
            return {
                activeTab: 0,
                center: {lat: 16.869607, lng: 96.195590},
                markers: [],
                mapControls: {
                    disableDefaultUI: true,
                    zoomControl: true,
                },
                mapStyle: {
                    width: '100%',
                    height: '0',
                },
                popHeight: {
                    maxHeight: '0',
                },
                currentPlace: null,
                linePath:[],
                options: {
                    strokeColor: '#415cab',
                    strokeOpacity: 0.9,
                    strokeWeight: 3,
                },
                icon: {
                    path: 0,
                    fillColor: '#ff9a02',
                    fillOpacity: 0.9,
                    scale: 6,
                    strokeColor: '#fff',
                    strokeOpacity: 0.9,
                    strokeWeight: 2
                },
                infoWinOpen: false,
                infoWindowPos: null,
                infoWindowTitle: '',
                infoWindowLineNub: '',
                loadingData: false,
                busLineName: '',
                busLineNo: '',
                tabWidth: 0,
                headBackColor: {
                    backgroundColor: '',
                },
                busLineListShow: false,
                listLoading: false,
                infoWindowStopInfo: { // 点击marker弹出popup后需要的信息
                    id: '',
                    name: '',
                    road: '',
                    township: '',
                },
                busLineList: [],
                userMarkers: {lat: 0, lng: 0},
                userLocationIcon: {
                    path: 0,
                    fillColor: '#448AFF',
                    fillOpacity: 0.9,
                    scale: 6,
                    strokeColor: '#fff',
                    strokeOpacity: 0.9,
                    strokeWeight: 1
                },
            };
        },
        methods: {
            closeClick() {
                this.infoWinOpen = false;
                return false;
            },
            showInfoWin(val) {
                this.infoWindowStopInfo = {
                    id: val.info.id,
                    name: this.translateString(val.info.nameMm) + ' - ' + val.info.nameEn,
                    road: this.translateString(val.info.roadMm) + ' - ' + val.info.roadEn,
                    township: this.translateString(val.info.townshipMm) + ' - ' + val.info.townshipEn,
                };
                this.infoWindowPos = val.position;
                this.infoWindowTitle = this.getTranslationName(val.info, 'name');
                this.infoWindowLineNub = this.getTranslationName(val.info, 'road');
                this.infoWinOpen = true;
            },
            initRoute(querys) {
                if (!querys) return false
                let  queryInfo= JSON.parse(querys)

                this.options.strokeColor = queryInfo.color;
                this.headBackColor.backgroundColor = queryInfo.color;
                this.busLineName = queryInfo.lineNum;
                this.busLineNo = queryInfo.lineNum;
                let _id = queryInfo.id;
                this.infoWinOpen = false;
                this.$nextTick(() => {
                    this.$refs.map.$mapPromise.then((map) => {
                        this.loadingData = true; // 不能v-show='loadingData = false' this.$refs.map.fitBound不生效，或者导致rooms混乱
                        this.getBusRouteDetail(_id);
                        this.initDom(map)
                    })
                })

            },
            initDom(map){
                let controlDiv = document.createElement('div');

                let firstChild = document.createElement('button');
                firstChild.style.backgroundColor = '#fff';
                firstChild.style.border = 'none';
                firstChild.style.outline = 'none';
                firstChild.style.width = '28px';
                firstChild.style.height = '28px';
                firstChild.style.borderRadius = '2px';
                firstChild.style.boxShadow = '0 1px 4px rgba(0,0,0,0.3)';
                firstChild.style.cursor = 'pointer';
                firstChild.style.marginRight = '10px';
                firstChild.style.padding = '0px';
                firstChild.title = 'Your Location';
                controlDiv.appendChild(firstChild);

                let secondChild = document.createElement('div');
                secondChild.style.margin = '5px';
                secondChild.style.width = '18px';
                secondChild.style.height = '18px';
                secondChild.style.backgroundImage = 'url(https://maps.gstatic.com/tactile/mylocation/mylocation-sprite-1x.png)';
                secondChild.style.backgroundSize = '180px 18px';
                secondChild.style.backgroundPosition = '0px 0px';
                secondChild.style.backgroundRepeat = 'no-repeat';
                secondChild.id = 'you_location_img';
                firstChild.appendChild(secondChild);
                controlDiv.index = 1;
                google.maps.event.addListener(map, 'dragend', () => {
                    let doc = document.getElementById('you_location_img')
                    doc.style.backgroundPosition = '0px 0px'
                });
                firstChild.addEventListener('click', () => {
                    let doc = document.getElementById('you_location_img')
                    let imgX = '0';
                    let animationInterval = setInterval( () =>{
                        if(imgX == '-18') imgX = '0';
                        else imgX = '-18';
                        doc.style.backgroundPosition = imgX+'0px 0px'
                    }, 500);
                    if(navigator.geolocation) {
                        navigator.geolocation.getCurrentPosition( (position) => {
                            // let latlng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
                            let latlng = {lat: position.coords.latitude, lng: position.coords.longitude};
                            this.userMarkers = latlng;
                            map.setCenter(latlng);
                            clearInterval(animationInterval);
                            doc.style.backgroundPosition = '-144px 0px'
                        });
                    }
                    else{
                        clearInterval(animationInterval);
                        doc.style.backgroundPosition = imgX+'0px 0px'
                    }
                });
                map.controls[google.maps.ControlPosition.RIGHT_BOTTOM].push(controlDiv);
            },
            getBusRouteDetail(id) {
                busRouteDetail(id).then((res) => {
                    if (res.data.data.errorID == 0) {
                        let stopArr = res.data.data.object;
                        const bounds = new google.maps.LatLngBounds()
                        for (let i=0; i<stopArr.length; i++){
                            let _o = {
                                lat : Number(stopArr[i].lat),
                                lng : Number(stopArr[i].lng),
                            };
                            let _i = {
                                id: stopArr[i].id,
                                nameEn: stopArr[i].nameEn,
                                nameMm: stopArr[i].nameMm,
                                roadEn: stopArr[i].roadEn,
                                roadMm: stopArr[i].roadMm,
                                townshipEn: stopArr[i].townshipEn,
                                townshipMm: stopArr[i].townshipMm,
                                selectedDate: stopArr[i].selectedDate,
                                status: stopArr[i].status,
                            };
                            let markersInfo = {
                                position: _o,
                                info: _i
                            };
                            // if (i == parseInt(stopArr.length/4) ){
                            //     this.center = _o  // 用下面的fitBound代替此功能
                            // }
                            bounds.extend(_o)
                            this.markers.push(markersInfo);
                            this.linePath.push(_o);
                            // this.loadingData = true;
                        }
                        this.$refs.map.fitBounds(bounds)
                    }else {
                        this.$toast(res.data.data.message)
                    }
                }).catch((error) => {
                    console.log(error)
                    this.$toast('error,please try again later')
                })
            },
            getBusLineListByStop(val) {
                if (val) {
                    this.infoWindowStopInfo = {
                        id: val.info.id,
                        name: this.translateString(val.info.nameMm) + ' - ' + val.info.nameEn,
                        road: this.translateString(val.info.roadMm) + ' - ' + val.info.roadEn,
                        township: this.translateString(val.info.townshipMm) + ' - ' + val.info.townshipEn,
                    };
                }
                this.busLineListShow = true;
                this.listLoading = true;
                this.busLineList = []
                let searchForm = {};
                searchForm.stopId = this.infoWindowStopInfo.id;
                busLineListByStop(searchForm).then((res) => {
                    if (res.data.data.errorID == 0) {
                        this.busLineList = res.data.data.object
                    } else {
                        this.$toast(res.data.data.message)
                    }
                    this.listLoading = false;
                }).catch((error) => {
                    console.log(error)
                    this.listLoading = false;
                    this.$toast('error,please try again later')
                })
            },
            translateString(str){
                if (!str) return ''
                return this.$translateLang(str,'unicodeTozawgyi');
            },
            getTranslationName(parent, name) {
                if (!parent) return
                let nameStr = name
                if (this.$store.state.store.localLang == 'MM') {
                    nameStr = nameStr + 'Mm'
                    return this.$translateLang(parent[nameStr],'unicodeTozawgyi')
                } else {
                    nameStr = nameStr + 'En'
                    return parent[nameStr]
                }
            },
            getLineNum(lineStr) {
                let str = lineStr;
                let _start = lineStr.indexOf("(");
                if (_start != -1) {
                    str = lineStr.substring(0, _start)
                }
                return str
            },
            getLineNumStr(lineStr) {
                let str = '';
                if (!lineStr) return
                let _start = lineStr.indexOf("(");
                let _end = lineStr.indexOf(")");
                if (_start != -1 && _end != -1) {
                    str = lineStr.substring(_start, _end+1)
                    str = this.$translateLang(str,'unicodeTozawgyi');
                    // if(this.$store.state.store.localLang == 'MM'){
                    //     str = this.$translateLang(str,'unicodeTozawgyi');
                    // }
                }
                return str
            },
            goToOtherLineData(info) {
                this.busLineListShow = false
                let path = this.$route.fullPath
                let queryObj = {
                    lineInfo: JSON.stringify(info),
                };
                this.$router.push({
                    path: path,
                    query:queryObj,
                })
            }
        },
        mounted() {
            this.mapStyle.height = document.body.clientHeight - 90 + 'px';
            this.popHeight.maxHeight = document.body.clientHeight - 40 + 'px';
            this.tabWidth = document.body.clientWidth/2 - 1;

            if (this.$route.query.lineInfo) {
                this.initRoute(this.$route.query.lineInfo);
            }
        },
        watch: {
            '$route' (to, from) {
                // 路由参数发生变化时
                if (this.$route) {
                    this.markers = []
                    this.linePath = []
                    this.activeTab = 0 // 保证地图可见，不然 this.$refs.map.fitBound时不生效，或者导致rooms混乱
                    if (this.$route.query.lineInfo) {
                        this.initRoute(this.$route.query.lineInfo);
                    }
                }
            },

        },
        beforeRouteLeave (to, from, next) {
            // 导航离开该组件的对应路由时调用
            // 可以访问组件实例 `this`
            // console.log(to,'to')
            let leave = true;
            if (this.busLineListShow) {
                this.busLineListShow = false
                leave = false
            }
            if (leave) {
                next()
            } else {
                next(false)
            }
        },
        beforeRouteUpdate (to, from, next) {
            // 导航离开该组件的对应路由时调用
            // 可以访问组件实例 `this`
            // console.log(to,'to')
            let leave = true;
            if (this.busLineListShow) {
                this.busLineListShow = false
                leave = false
            }
            if (leave) {
                next()
            } else {
                next(false)
            }
        },

    };
</script>
<style>
    .busLine-by-id .van-nav-bar{
        background-color: #fff;
        /*background-color: #f2f2f2;*/
        color: #333;
        z-index: 9;
    }
    .busLine-by-id .van-nav-bar .van-icon{
        color: #C8C8C8;
        margin-right: 15px;
        font-size: 18px;
    }
    .busLine-by-id .van-nav-bar .van-nav-bar__title{
        color: #333;
    }
    .van-tabs__nav .van-tab{
       border-right: 1px solid #eee;
    }
    .van-tabs__nav .van-tab:last-child{
        border-right: none;
    }
    .bus-line-pop.van-popup{
        width: 85%;
        /*max-height: 90%;*/
        border-radius: 4px;
    }
    .bus-line-pop .van-loading{
        display: inline-block;
    }
</style>
<style scoped>
    .g-font {
        font-family: Zawgyi-One, 'Avenir', Helvetica, Arial, sans-serif!important;
    }
    .info-title{
        display: flex;
    }
    .info-title .title-left{
        color: #ff4181;
        flex: 1;
    }
    .info-title .title-right{
        width: 10px;
        margin-left: 15px;
        position: relative;
    }
    .info-title .title-right:before{
        content: "";
        position: absolute;
        border-top: 1px solid #000;
        border-right: 1px solid #000;
        width: 7px;
        height: 7px;
        top: 50%;
        left: 50%;
        margin-left: -5px;
        margin-top: -4px;
        transform: rotate(45deg);
    }
    .stop-list-item {
        display: flex;
        align-items: center;
        /*padding: 4% 8px;*/
        /*border-bottom: 1px solid #eee;*/

        padding: 4px;
        border: 1px solid #eee;
        margin: 8px 2%;
        border-radius: 4px;
        box-shadow:2px 2px 3px #ddd;
    }
    .stop-list-item:active{
        background: #eee;
    }
    .item-left{
        width: 60px;
        height: 60px;
        background: brown;
        line-height: 60px;
        text-align: center;
        color: #fff;
    }
    .item-right{
        flex: 1;
        margin-left: 10px;
    }
    .item-right .item-title{
        color: rgb(219, 55, 67);
    }
    .list-loading{
        width: 100%;
        text-align: center;
        padding: 15px 0;
    }
    .line-list-box{
        height: 100%;
        padding: 8px 3%;
        display: flex;
        flex-flow: column;
        overflow: hidden;
    }
    .line-list-title{
        /*position: absolute;*/
        /*top: 8px;*/
        /*left: 3%;*/
        /*right: 3%;*/
    }
    .line-list-title .line-title{
        color: rgb(219, 55, 67);
        font-size: 16px;
    }
    .line-list-outbox{
        flex: 1;
        overflow-y: scroll;
        overflow-x: hidden;
    }
</style>
